<template>
    <div class="robotChannel channelContainer">
        <div class="channelList" v-show="!editShow">
            <div class="header flexbetween" style="margin-bottom: 20px">
                <div></div>
                <div class="iconBtn">
                    <el-tooltip effect="light" content="添加" placement="top" :enterable="false" v-if="menuAuthCodes.includes('M108')">
                        <span class="iconfont icon-tianjia" @click="addOpen"></span>
                    </el-tooltip>
                </div>
            </div>
            <element-table :data="channelList" :columns="cloumns" :loading="tableLoading" :tableHeight="tableHeight" :pageNo="pageNo"
                           :pageSize="pageSize" :total="total" @changePageNo="changePageNo" @changePageSize="changePageSize">
            </element-table>
        </div>
        <div class="editContaner" v-if="editShow">
            <div class="header flexbetween mb20">
                <span>机器人编辑</span>
                <el-button size="small" plain @click="returnList(false)">返回列表</el-button>
            </div>
            <div class="titleConfig flexbetween mb20">
                <p><span>个性化配置</span>开启后，支持按不同的入口对机器人欢迎语、引导卡片、兜底话术、快捷入口等进行个性化内容配置【否则采用“默认窗口配置”】</p>
                <el-switch v-model="customStatus" :active-value="1" :inactive-value="0"></el-switch>
            </div>
            <channelConfig ref="channelConfig" v-show="customStatus == 1"></channelConfig>
            <div class="buttomBtn">
                <el-button size="small" plain @click="returnList(false)">取消</el-button>
                <el-button size="small" type="primary" @click="submit">保存</el-button>
            </div>
        </div>

        <!-- 添加渠道 -->
        <el-dialog :title="channelTitle" :visible="addChannelVisible" width="640px" @close="addChannelClose" class="addChannelDialog">
            <el-form :model="sourceForm" :rules="sourceFormRules" ref="sourceForm" label-width="120px">
                <el-form-item label="渠道名称" prop="sourceName">
                    <el-input v-model="sourceForm.sourceName" placeholder="请输入渠道" size="small" style="width: 400px"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addChannelClose" size="small" type="text">取 消</el-button>
                <el-button type="primary" size="small" @click="addChannelSubmit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import elementTable from "@/components/elementTable";
import channelConfig from "@/components/channelConfig";
import { getSourceList, addBaseSource, editBaseSource, addSource, editSource, delSource } from "@/api/channel.js";
import { merge } from "lodash";
import { mapGetters } from "vuex";
export default {
    name: "robotChannel",
    data() {
        return {
            type: "",
            channelList: [],
            tableLoading: false,
            pageNo: 1,
            pageSize: 10,
            total: 0,
            cloumns: [
                {
                    config: {
                        label: "渠道号",
                        prop: "id"
                    },
                },
                {
                    config: {
                        label: "渠道名称",
                        prop: "sourceName",
                    },
                    render: (h, scope) => {
                        return (<el-link type="primary" underline={false} onClick={() => this.editSource(scope)}>{scope.sourceName}</el-link>)
                    }
                },
                {
                    config: {
                        label: "创建时间",
                        prop: "addTime",
                    }
                },
                {
                    config: {
                        label: "渠道类型",
                    },
                    render: (h, scope) => {
                        var sourceType = {
                            "web": "网页",
                            "weixin": "微信",
                            "api": "API"
                        }
                        return (<span>{sourceType[scope.type]}</span>)
                    }
                },
                {
                    config: {
                        label: "操作",
                        width: "100"
                    },
                    render: (h, scope) => {
                        return (
                            <div class="operation">
                                <el-tooltip effect="light" content="编辑" placement="top" enterable={false}
                                    v-show={this.menuAuthCodes.includes('M110')}>
                                    <span class="iconfont icon-bianjidaan" onClick={() => this.editOpen(scope)}></span>
                                </el-tooltip>
                                <el-tooltip effect="light" content="删除" placement="top" enterable={false}
                                    v-show={this.menuAuthCodes.includes('M109')}>
                                    <span class="iconfont icon-shanchu" onClick={() => this.delSource(scope.id)}></span>
                                </el-tooltip>
                            </div>
                        );
                    },
                }
            ],
            editType: "add",
            editShow: false,
            editId: "",
            customStatus: 0, //个性化配置
            addChannelVisible: false,
            channelType: "add",
            sourceName: "",
            sourceForm: {
                sourceName: "",
            },
            sourceFormRules: {
                sourceName: [{ required: true, message: '请输入渠道名称', trigger: 'blur' }]
            },
            channelForm: {
                robotName: "",
                robotAvatarUrl: "",
                knowledgeSetIds: [],
                welcome: [
                    {
                        type: 1,
                        value: ""
                    }
                ],
                welcomeRecStatus: 0,
                welcomePreDesc: "",
                welcomeRecQuestionType: 1,
                welcomeRecQuestions: [],
                unknownDesc: {
                    type: 1,
                    value: ""
                },
                unknownManTakeStatus: 0,
                unknownManTakeType: 1,
                unknownManTakeTimes: 1,
                unknownRecStatus: 0,
                unknownRecDesc: "",
                unknownRecType: 1,
                unknownRecQuestions: [],
                greetingStatus: 0,
                guideCards: [],
                guideCapsules: []
            },
        }
    },
    created() {
        this.type = this.$route.path.split("/")[2];
        this.getSourceList();
    },
    methods: {
        //获取渠道列表
        getSourceList() {
            if (!this.menuAuthCodes.includes("M107")) {
                return;
            }
            this.tableLoading = true;
            var param = {
                pageNo: this.pageNo,
                pageSize: this.pageSize,
                type: this.type
            }
            getSourceList(param).then(resp => {
                this.tableLoading = false;
                if (resp.status == 0) {
                    var data = resp.data;
                    this.total = data.total;
                    this.channelList = data.list;
                } else {
                    this.$antMessage.warning(resp.message);
                }
            });
        },
        addOpen() {
            this.channelType = "add";
            this.addChannelVisible = true;
        },
        editSource(data) {
            this.channelType = "edit";
            this.editId = data.id;
            this.sourceForm.sourceName = data.sourceName;
            this.addChannelVisible = true;
        },
        editOpen(data) {
            this.editShow = true;
            this.editType = "edit";
            this.editId = data.id;
            this.customStatus = data.customStatus || 0;
            this.sourceName = data.sourceName;
            var fromDate = merge({}, this.channelForm, data);
            this.$nextTick(() => {
                this.$refs.channelConfig.setFromData(fromDate);
            });
        },
        changePageSize(val) {
            this.pageSize = val;
            this.getSourceList();
        },
        changePageNo(val) {
            this.pageNo = val;
            this.getSourceList();
        },
        submit() {
            if (this.customStatus == 0) {
                var param = {}, index, data;
                index = this.channelList.findIndex(item => item.id == this.editId);
                data = this.channelList[index] || [];
                if (data.robotName) {
                    for (let key in data) {
                        param[key] = data[key];
                    }
                } else {
                    for (let key in this.channelForm) {
                        param[key] = this.defaultSourceConfig[key];
                    }
                }
            } else {
                var param = this.$refs.channelConfig.getFromData();
            }
            if (param) {
                param.sourceName = this.sourceName;
                param.customStatus = this.customStatus;
                param.type = this.type;
                // if (this.editType == "add") {
                //     addSource(param).then(resp => {
                //         if (resp.status == 0) {
                //             this.$antMessage.success("添加成功");
                //             this.returnList(true);
                //             this.$eventBus.$emit('updateSource');
                //         } else {
                //             this.$antMessage.warning(resp.message);
                //         }
                //     });
                // } else {
                param.id = this.editId;
                editSource(param).then(resp => {
                    if (resp.status == 0) {
                        this.$antMessage.success("编辑成功");
                        this.returnList(true);
                        this.$eventBus.$emit('updateSource');
                    } else {
                        if (this.customStatus == 0 && resp.code == 4000 && false) {
                            this.$antMessage.warning("请先配置完整默认窗口配置");
                        } else {
                            this.$antMessage.warning(resp.message);
                        }
                    }
                });
                // }
            }
        },
        delSource(id) {
            this.$confirm("是否确定删除?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                delSource({ ids: id }).then((resp) => {
                    if (resp.status == 0) {
                        this.$antMessage.success("删除成功");
                        this.getSourceList();
                    } else {
                        this.$antMessage.warning(resp.message);
                    }
                });
            }).catch();
        },
        returnList(reload) {
            if (reload) {
                this.getSourceList();
            }
            // this.$refs.channelConfig.clearFromData();
            this.editShow = false;
        },
        addChannelSubmit() {
            this.$refs.sourceForm.validate((valid) => {
                if (valid) {
                    var param = {
                        type: this.type,
                        sourceName: this.sourceForm.sourceName
                    }
                    if (this.channelType == "add") {
                        addBaseSource(param).then(resp => {
                            if (resp.status == 0) {
                                this.pageNo = 1;
                                this.getSourceList();
                                this.addChannelClose();
                                this.$antMessage.success("添加成功");
                                this.$eventBus.$emit('updateSource');
                            } else {
                                this.$antMessage.warning(resp.message);
                            }
                        });
                    } else {
                        param.id = this.editId;
                        editBaseSource(param).then(resp => {
                            if (resp.status == 0) {
                                this.getSourceList();
                                this.addChannelClose();
                                this.$antMessage.success("添加成功");
                                this.$eventBus.$emit('updateSource');
                            } else {
                                this.$antMessage.warning(resp.message);
                            }
                        });
                    }

                }
            });
        },
        addChannelClose() {
            this.sourceForm.sourceName = "";
            this.$refs.sourceForm.resetFields();
            this.addChannelVisible = false;
        }
    },
    computed: {
        ...mapGetters(["defaultSourceConfig"]),
        tableHeight() {
            return document.body.clientHeight - 240;
        },
        channelTitle() {
            return this.channelType == "add" ? "添加渠道" : "编辑渠道";
        }
    },
    provide() {
        return {
            sourceId: () => this.editId
        }
    },
    components: {
        elementTable,
        channelConfig
    }
}
</script>

<style lang="scss">
.robotChannel {
    height: calc(100% - 40px);
    .mb0 {
        margin-bottom: 0 !important;
    }
    .editContaner {
        height: 100%;
        .el-form-item__label,
        .el-form-item__content,
        .el-input--small .el-input__icon {
            line-height: 34px;
        }
        .header {
            > span {
                color: #363c43;
                font-size: 16px;
                padding-left: 8px;
                border-left: 2px solid #6b5ee2;
            }
        }
        .titleConfig {
            height: 48px;
            border-radius: 6px;
            background: #f5f7fa;
            padding: 0 20px;
            p {
                color: #676e75;
                span {
                    color: #363c43;
                    margin-right: 15px;
                }
            }
        }
        .buttomBtn {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            height: 60px;
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: #fff;
            padding-right: 20px;
            width: calc(100% - 330px);
            border-radius: 0 0 20px 20px;
            box-shadow: 0px 3px 15px 0px rgba(102, 112, 123, 0.3);
            .el-button {
                margin-left: 20px;
            }
        }
    }
    .channelConfig {
        height: calc(100% - 145px) !important;
    }
}
</style>